import React, { useEffect, useRef, useImperativeHandle, useState } from 'react';
import { DanmakuController } from './controller';
import EmojiPicker from './EmojiPicker';

interface Props {
  targetSelector?: string; // 可选：用于定位视频容器大小的选择器
}

export type DanmakuHandle = {
  send: (text: string) => void;
  sendBottom: (text: string) => void;
  sendTop: (text: string) => void;
  sendEmoji: (emoji: string) => void;
  showEmojiPicker: () => void;
  clear: () => void;
  setOpacity: (v: number) => void;
  setSpeedRange: (range: [number, number]) => void;
  setFixedSpeed: (speed: number) => void;
  setGlobalDisplayMode: (mode: 'scroll' | 'top' | 'bottom') => void;
  setEnabled: (enabled: boolean) => void;
  getEnabled: () => boolean;
};

const DanmakuCanvas = React.forwardRef<DanmakuHandle, Props>((_props, ref) => {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const controllerRef = useRef<DanmakuController | null>(null);
  const containerRef = useRef<HTMLDivElement | null>(null);
  type HistItem = { text: string; ts: number; mode?: 'bottom' | 'top' };
  const historyRef = useRef<HistItem[]>([]);
  const emittedRef = useRef<boolean[]>([]);
  const timerRef = useRef<number | null>(null);
  const lastSendRef = useRef<number>(0);
  const minIntervalMsRef = useRef<number>(800); // 最小发送间隔
  const bannedRef = useRef<string[]>([ 'fuck', '草', '妈的','傻逼']);
  
  // 表情选择器状态
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);

  function escapeRegExp(s: string) {
    return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  }

  function filterText(input: string): string {
    if (!input) return input;
    const words = bannedRef.current.filter(Boolean);
    if (words.length === 0) return input;
    const pattern = new RegExp(words.map(escapeRegExp).join('|'), 'gi');
    return input.replace(pattern, (m) => '*'.repeat(Math.min(4, m.length)));
  }

  // 处理表情选择
  const handleEmojiSelect = (emoji: string) => {
    const now = Date.now();
    if (now - lastSendRef.current < minIntervalMsRef.current) {
      return; // 过快，丢弃本次发送
    }
    lastSendRef.current = now;
    
    // 直接发送表情，不添加到历史记录中，避免重复发送
    controllerRef.current?.send(emoji);
  };

  useEffect(() => {
    const canvas = canvasRef.current!;
    const container = containerRef.current!;
    
    // 使用视频播放器的实际尺寸（750px × 370px）作为Canvas尺寸
    const videoWidth = 750;
    const videoHeight = 370;
    
    controllerRef.current = new DanmakuController(canvas, videoWidth, videoHeight, {});
    controllerRef.current.start();

    // 找到同容器内的视频元素
    const videoEl = container.parentElement?.querySelector('video.demo-video') as HTMLVideoElement | null;

    const seedDemo = () => {
      const now = videoEl?.currentTime || 0;
      // 读取本地历史（带时间戳）
      try {
        const ls = localStorage.getItem('dmHistory');
        if (ls) historyRef.current = JSON.parse(ls);
      } catch {}
      // 演示弹幕：分配到当前时间后稍许
      const demoTexts = ['Hello 弹幕', '随机颜色', '随机速度', '本地实现 OK', '🎉🎉🎉'];
      const demos: HistItem[] = demoTexts.map((t, i) => ({ text: t, ts: now + 0.5 + i * 0.4 }));
      historyRef.current = [...demos, ...historyRef.current];
      emittedRef.current = historyRef.current.map(it => it.ts < now);
    };

    const startSync = () => {
      if (!videoEl) return;
      if (timerRef.current != null) return;
      const tick = () => {
        const ct = videoEl.currentTime;
        const list = historyRef.current;
        for (let i = 0; i < list.length; i++) {
          if (emittedRef.current[i]) continue;
          if (list[i].ts <= ct + 0.02) {
             controllerRef.current?.send(list[i].text);
            emittedRef.current[i] = true;
          }
        }
        timerRef.current = window.setTimeout(tick, 100);
      };
      timerRef.current = window.setTimeout(tick, 100);
    };

    const stopSync = () => {
      if (timerRef.current != null) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }
    };

    const onResize = () => {
      const r = container.getBoundingClientRect();
      controllerRef.current?.resize(r.width, r.height);
    };
    window.addEventListener('resize', onResize);

    // 初次注入演示弹幕
    seedDemo();

    // seek/播放：根据当前位置重建可播放集合
    const onSeeked = () => {
      if (!videoEl) return;
      controllerRef.current?.clear();
      const now = videoEl.currentTime;
      emittedRef.current = historyRef.current.map(it => it.ts < now);
    };
    videoEl?.addEventListener('seeked', onSeeked);
    videoEl?.addEventListener('loadeddata', onSeeked);
    videoEl?.addEventListener('play', () => { onSeeked(); startSync(); });
    videoEl?.addEventListener('pause', () => { stopSync(); });

    return () => {
      window.removeEventListener('resize', onResize);
      videoEl?.removeEventListener('seeked', onSeeked);
      videoEl?.removeEventListener('loadeddata', onSeeked);
      videoEl?.removeEventListener('play', () => {});
      videoEl?.removeEventListener('pause', () => {});
      stopSync();
      controllerRef.current?.stop();
    };
  }, []);

  useImperativeHandle(ref, () => ({
    send: (text: string) => {
      const t = text || '';
      const now = Date.now();
      if (now - lastSendRef.current < minIntervalMsRef.current) {
        return; // 过快，丢弃本次发送
      }
      lastSendRef.current = now;
      const safeText = filterText(t).slice(0, 80);
      if (!safeText.trim()) return;
      // 直接发送，不添加到历史记录中，避免重复发送
      controllerRef.current?.send(safeText);
    },
    sendBottom: (text: string) => {
      const t = text || '';
      const now = Date.now();
      if (now - lastSendRef.current < minIntervalMsRef.current) return;
      lastSendRef.current = now;
      const safeText = filterText(t).slice(0, 80);
      if (!safeText.trim()) return;
      // 直接发送，不添加到历史记录中，避免重复发送
      controllerRef.current?.send(safeText);
    },
    sendTop: (text: string) => {
      const t = text || '';
      const now = Date.now();
      if (now - lastSendRef.current < minIntervalMsRef.current) return;
      lastSendRef.current = now;
      const safeText = filterText(t).slice(0, 80);
      if (!safeText.trim()) return;
      // 直接发送，不添加到历史记录中，避免重复发送
      controllerRef.current?.send(safeText);
    },
    sendEmoji: (emoji: string) => {
      handleEmojiSelect(emoji);
    },
    showEmojiPicker: () => {
      setShowEmojiPicker(true);
    },
    clear: () => controllerRef.current?.clear(),
    setOpacity: (v: number) => controllerRef.current && (controllerRef.current as any).config ? ((controllerRef.current as any).config.opacity = v) : controllerRef.current?.['setOpacity' as any]?.(v),
    setSpeedRange: (range: [number, number]) => controllerRef.current?.['setSpeedRange' as any]?.(range),
    setFixedSpeed: (speed: number) => {
      // console.log('DanmakuCanvas接收到速度设置:', speed);
      controllerRef.current?.setFixedSpeed?.(speed);
    },
    setGlobalDisplayMode: (mode: 'scroll' | 'top' | 'bottom') => controllerRef.current?.['setGlobalDisplayMode' as any]?.(mode),
    setEnabled: (enabled: boolean) => controllerRef.current?.setEnabled(enabled),
    getEnabled: () => controllerRef.current?.getEnabled() ?? true,
  }), []);

  return (
    <>
      <div ref={containerRef} className="danmaku-layer" style={{ position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 2 }}>
        <canvas 
          ref={canvasRef} 
          style={{ 
            width: '750px', 
            height: '370px', 
            display: 'block',
            marginLeft: '88px',
            marginTop: '76px',
            borderRadius: '30px'
          }} 
        />
      </div>
      
      <EmojiPicker
        isVisible={showEmojiPicker}
        onEmojiSelect={handleEmojiSelect}
        onClose={() => setShowEmojiPicker(false)}
      />
    </>
  );
});

export default DanmakuCanvas;


